<template>
	<view class="customerManage">
		<uni-nav-bar fixed left-icon="left" title="客户管理" @clickLeft="backHandle" class="unibarS">
			<block slot="right">
				<text class="sub-btn" @click="goCustomer()">新增</text>
			</block>
		</uni-nav-bar>
		<u-sticky offset-top="0">
			<dropdown-screen
				ref="dropdownScreen"
				:barFontSize="32"
				:barTextColor="'rgba(12, 16, 25, 1)'"
				:activeColor="'rgba(77, 172, 177, 1)'"
				@tabClick="tabClick"
				@confirm="confirm"
				@reset="reset"
				:listArr="listArr">
				<template v-slot:content>
					<view class="searchContent" v-show="searchType == 0">
						<u--form labelPosition="top" ref="uForm" labelWidth="70">
							<u-form-item label="排序方式" ref="item1">
								<radio-group @change="radioChange($event, 'sortKeyValues')" class="radio-group-box">
									<label>
										<radio value="desc" :checked="tempSearchObj.sortKeyValues === 'desc'" iconColor="#FFFFFF" activeBackgroundColor="#4DACB1" />
										<text>倒序排序</text>
									</label>
									<label>
										<radio value="asc" :checked="tempSearchObj.sortKeyValues === 'asc'" iconColor="#FFFFFF" activeBackgroundColor="#4DACB1" />
										<text>正序排序</text>
									</label>
								</radio-group>
							</u-form-item>
							<u-form-item label="排序属性" ref="item1">
								<radio-group @change="radioChange($event, 'sortKey')" class="radio-group-box">
									<label v-for="(item, index) in sortPropsList" :key="index">
										<radio :value="item.value" :checked="tempSearchObj.sortKey === item.value" iconColor="#FFFFFF" activeBackgroundColor="#4DACB1" />
										<text>{{ item.name }}</text>
									</label>
								</radio-group>
							</u-form-item>
						</u--form>
					</view>
					<view class="searchContent" v-show="searchType == 1">
						<u--form labelPosition="top" ref="uForm" labelWidth="100">
							<u-form-item label="客户分类" ref="item1">
								<radio-group @change="radioChange($event, 'customerRoleType')" class="radio-group-box">
									<label v-for="(item, index) in customerRoleTypeList" :key="index">
										<radio :value="item.value" :checked="tempSearchObj.customerRoleType === item.value" iconColor="#FFFFFF" activeBackgroundColor="#4DACB1" />
										<text>{{ item.name }}</text>
									</label>
								</radio-group>
							</u-form-item>
							<u-form-item label="客户类型" ref="item1">
								<!-- <checkbox-group @change="changegroup($event, 'customerType')" class="checkbox-group-box">
									<label v-for="(item, index) in bus_client_type" :key="index">
										<checkbox :value="item.value" style="transform:scale(0.7)" iconColor="#FFFFFF" activeBackgroundColor="#4DACB1" activeBorderColor="#4DACB1" /> {{ item.dictLabel }}
									</label>
								</checkbox-group> -->
								<radio-group @change="radioChange($event, 'customerType')" class="radio-group-box">
									<label v-for="(item, index) in bus_client_type" :key="index">
										<radio :value="item.dictValue" :checked="tempSearchObj.customerType === item.dictValue" iconColor="#FFFFFF" activeBackgroundColor="#4DACB1" />
										<text>{{ item.dictLabel }}</text>
									</label>
								</radio-group>
							</u-form-item>
							<u-form-item label="客户状态" ref="item1">
								<radio-group @change="radioChange($event, 'customerStatus')" class="radio-group-box">
									<label v-for="(item, index) in bus_customer_status" :key="index">
										<radio :value="item.dictValue" :checked="tempSearchObj.customerStatus === item.dictValue" iconColor="#FFFFFF" activeBackgroundColor="#4DACB1" />
										<text>{{ item.name }}</text>
									</label>
								</radio-group>
							</u-form-item>
							<u-form-item label="客户星级" ref="item1">
								<radio-group @change="radioChange($event, 'customerStarLevel')" class="radio-group-box">
									<label v-for="(item, index) in bus_customer_starlevel" :key="index">
										<radio :value="item.dictValue" :checked="tempSearchObj.customerStarLevel === item.dictValue" iconColor="#FFFFFF" activeBackgroundColor="#4DACB1" />
										<text>{{ item.name }}</text>
									</label>
								</radio-group>
							</u-form-item>
							<u-form-item label="下次跟进时间" ref="item1">
								<radio-group @change="radioChange($event, 'timeType')" class="radio-group-box">
									<label v-for="(item, index) in tiemList" :key="index">
										<radio :value="item.value" :checked="tempSearchObj.timeType === item.value" iconColor="#FFFFFF" activeBackgroundColor="#4DACB1" />
										<text>{{ item.name }}</text>
									</label>
								</radio-group>
							</u-form-item>
							<u-form-item class="search-item-box" label="所在地区" @click="selectCityHandle()" border ref="item1">
								<view>
									<view>{{ tempSearchObj.localAreaName || '请选择地区' }}</view>
								</view>
								<u-icon slot="right" name="arrow-right"></u-icon>
							</u-form-item>
							<u-form-item class="search-item-box" label="创建时间"  @click="openCalendar()" border ref="item1">
								<view>
									<view>{{ tempSearchObj.createTimes || '选择时间范围' }}</view>
								</view>
								<u-icon slot="right" name="clock"></u-icon>
							</u-form-item>
							<!-- <u-form-item label="客户状态" ref="item1">
								<u--input border="true" placeholder="请输入客户手机号" :custom-style="{ border: '1px solid rgba(103, 117, 133, 0.4)' }"></u--input>
							</u-form-item> -->
						</u--form>
					</view>
				</template>
			</dropdown-screen>
		</u-sticky>
		<uni-search-bar class="uni-mt-10" v-model="params.keyWords" bgColor="#FFFFFF" radius="5" placeholder="搜索"
			clearButton="auto" cancelButton="none" @confirm="searchHandle()" @clear="searchHandle()" />
		<template v-if="list.length">
			<view class="list">
				<view class="item" v-for="item in list" :key="item.id">
					<view class="item-top" @click="goCustomerDetail(item)">
						<view class="item-top-left">
							<view class="name">{{ item.customerName }}<text style="margin-left: 20rpx;">{{ item.phoneNumber }}</text></view>
							<view class="rate">客户星级：<u-rate v-model="item.customerStarLevel" readonly
									activeColor="#FFC300"></u-rate></view>
							<view class="time">最后跟进：{{ item.latestFollowupTime || '---' }}</view>
						</view>
						<view class="item-top-right">
							<u-avatar :src="item.avatar" @click.native.stop="goStaffDetails(item)"></u-avatar>
							<view class="salesman">{{ item.businessManagerName }}</view>
						</view>
					</view>
					<view class="item-bottom">
						<view @click="addFollow(item)">
							<u-icon name="file-text-fill" color="#677585FF" size="24"></u-icon>
							<text>跟进登记</text>
						</view>
						<view @click="addOrder(item)">
							<u-icon name="plus-square-fill" color="#677585FF" size="24"></u-icon>
							<text>新建订单</text>
						</view>
						<view @click="goCustomerDetail(item)">
							<text>查看详情</text>
							<u-icon name="arrow-right" color="#677585FF" size="18"></u-icon>
						</view>
					</view>
				</view>
			</view>
			<uni-load-more :status="status" />
		</template>
		<empty-view v-else></empty-view>

        <!-- 选择跟进日期 -->
        <uni-calendar ref="calendar" class="uni-calendar--hook" :range="true" :clear-date="true" :date="info.date"
            :insert="info.insert" @confirm="confirmCalendar" @close="closeCalendar" />
	</view>
</template>

<script>
import dropdownScreen from '@/components/dropdown-screen/dropdown-screen'
import { calculateDateRange } from '@/common/utils'
export default {
	components: {
		dropdownScreen
	},
	data() {
		return {
			params: {
				keyWords: '',
				pageNum: 1,
				pageSize: 20,
				
				sortKey: 'create_time',
				sortKeyValues: 'desc',
				timeType: null,
				followUpTime: null,
				localArea: null,
				localAreaName: null,
				customerRoleType: null,
				customerType: null,
				customerStatus: null,
				customerStarLevel: null,
				createTimes: null
			},
			total: 0,
			status: 'loading',
			refresh: false,
			list: [],
			listArr: [
				{
					label: '排序',
					iconPath: '/static/svg/icon-paixu.svg'
				},
				{
					label: '筛选',
					iconPath: '/static/svg/icon-shaixuan.svg'
				}
			],
			// 排序0  筛选1
			searchType: 0,
			showCalendar: true, // 显示日历
			sortPropsList: [
				{ name: '创建时间', value: 'create_time' },
				{ name: '客户名称', value: 'customer_name' },
				{ name: '成交总额', value: 'order_total_amount' },
				{ name: '回款金额', value: 'payment_amount' }
			],
			// 客户分类
			customerRoleTypeList: [
				{ name: '我的客户', value: '1' },
				{ name: '重点客户', value: '2' },
				{ name: '今日新增', value: '3' }
			],
			tiemList: [
				{ 	name: '今年', value: '1'  },
				{ 	name: '本季度', value: '2'  },
				{ 	name: '上季度', value: '3'  },
				{ 	name: '本月', value: '4'  },
				{ 	name: '上月', value: '5'  },
				{ 	name: '本周', value: '6'  },
				{ 	name: '上周', value: '7'  },
				{ 	name: '昨天', value: '8'  },
				{ 	name: '今天', value: '9'  },
			],
			info: {
                insert: false,
                selected: []
            },
			tempSearchObj: {
				sortKey: 'create_time',
				sortKeyValues: 'desc',
				timeType: null,
				followUpTime: null,
				localArea: null,
				localAreaName: null,
				customerRoleType: null,
				customerType: null,
				customerStatus: null,
				customerStarLevel: null,
				createTimes: null
			}
		}
	},
	onLoad() {
		this.bus_client_type = JSON.parse(uni.getStorageSync('bus_client_type'))
		this.bus_customer_status = JSON.parse(uni.getStorageSync('bus_customer_status'))
		this.bus_customer_starlevel = JSON.parse(uni.getStorageSync('bus_customer_starlevel'))

		this.getData()
	},
	onReachBottom() {
		console.log('上拉加载onReachBottom')
		if (this.status == 'noMore' || this.status == 'loading') return
		this.params.pageNum = this.params.pageNum + 1
		this.status = 'loading'
		this.getData()
	},
	onPullDownRefresh() {
		this.$refs.dropdownScreen.maskClose()
		this.refresh = true
		this.params.pageNum = 1
		this.list = []
		this.searchHandle()
	},
	methods: {
		getData() {
			this.$http.get('/app/customer/list', this.params).then(res => {
				if (res.code == 200) {
					this.list = [...this.list, ...res.rows]
					this.total = res.total
					if (this.total > this.list.length) {
						this.status = 'more'
					} else {
						this.status = 'noMore'
					}
					if (this.refresh) {
						uni.stopPullDownRefresh()
					}
				} else {
					uni.$u.toast(res.msg)
				}
			})
		},
		searchHandle() {
			this.params.pageNum = 1
			this.status = 'loading'
			this.list = []
			this.getData()
		},
		goCustomerDetail(item) {
			uni.navigateTo({
				url: '/pages/crm/customer/customerDetails?id=' + item.id
			})
		},
		addOrder(item) {
			uni.navigateTo({
				url: '/pages/order/addOrder?cName=' + item.customerName + '&cId=' + item.id
			})
		},
		goCustomer() {
			uni.navigateTo({
				url: '/pages/crm/customer/createCustomer'
			});
		},
		// 新建跟进
		addFollow(item) {
			uni.navigateTo({
				url: '/pages/follow/addFollow?cName=' + item.customerName + '&cId=' + item.id
			});
		},
		// 员工详情
		goStaffDetails(item) {
			uni.navigateTo({
				url: '/pages/other/staffDetails?id=' + item.businessManagerId
			});
		},
		selectCalendar() {
			console.log('点击了')
			this.showCalendar = true
		},
		// 打开日历
		openCalendar(type) {
            this.$refs.calendar.open()
        },
        // 确定日期
        confirmCalendar(e) {
			console.log(e)
			if(e.range.before && e.range.after) {
				let arr = []
				arr[0] = e.range.before? e.range.before + ' 00:00:00' : null
				arr[1] = e.range.after? e.range.after + ' 23:59:59' : null
				this.tempSearchObj.createTimes = arr.join(',')
				console.log(this.tempSearchObj.createTimes)
			} else {
				this.tempSearchObj.createTimes = null
				// uni.$u.toast('请选择时间范围')
				return
			}
        },
        // 关闭日历
        closeCalendar() { },
		// 去选择城市
		selectCityHandle() {
            let that = this
            uni.navigateTo({
                url: '/pages/other/selectCity',
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    someEvent: function (data) {
						console.log(data)
                        // that.params.localProvince = data.data.localProvince.code
                        // that.params.localProvinceName = data.data.localProvince.name
                        // that.params.localCity = data.data.localCity.code
                        // that.params.localCityName = data.data.localCity.name
                        that.tempSearchObj.localArea = data.data.localCounty.code
                        that.tempSearchObj.localAreaName = data.data.localCounty.name
                    },
                },
                success: function (res) {

                }
            });
        },
		radioChange(e, props) {
			// console.log(e)
			// console.log(props)
			this.tempSearchObj[props] = e.detail.value
			if(props == 'timeType') {
				const [start, end] = calculateDateRange(this.tempSearchObj.timeType)
				let startTime = start
				let endTime = end
				this.tempSearchObj.followUpTime = startTime + ',' + endTime
			}
		},
		changegroup(e, props) {
			console.log(e)
			console.log(props)
			this.tempSearchObj[props] = e.detail.value
		},
		// 点击了 切换了 搜索标签
		tabClick(item) {
            Object.keys(this.params).forEach(key => {
				if (this.tempSearchObj.hasOwnProperty(key)) {
					this.tempSearchObj[key] = this.params[key];
				}
			});
			this.searchType = item.index
		},
		reset() {
			this.tempSearchObj = {
				sortKey: 'create_time',
				sortKeyValues: 'desc',
				timeType: null,
				followUpTime: null,
				localArea: null,
				localAreaName: null,
				customerRoleType: null,
				customerType: null,
				customerStatus: null,
				customerStarLevel: null,
				createTimes: null
			}
			Object.keys(this.tempSearchObj).forEach(key => {
				if (this.params.hasOwnProperty(key)) {
					this.params[key] = this.tempSearchObj[key];
				}
			});
			this.searchHandle()
		},
		confirm() {
			Object.keys(this.tempSearchObj).forEach(key => {
				if (this.params.hasOwnProperty(key)) {
					this.params[key] = this.tempSearchObj[key];
				}
			});
			this.searchHandle()
		},
		backHandle() {
			uni.navigateBack()
		},
		submit() {

		},
		search() { }
	}
}
</script>

<style lang="scss" scoped>
/deep/.u-sticky {
	z-index: 10 !important;
}
.customerManage {
	background: rgba(247, 248, 250, 1);
}

.item {
	padding: 32rpx;
	border-radius: 24rpx;
	background: rgba(255, 255, 255, 1);
	margin-bottom: 20rpx;

	.item-top {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.item-top-left {
			flex: 1;
			margin-right: 20rpx;
			width: 0;

			.name {
				font-size: 32rpx;
				font-weight: 500;
				color: rgba(12, 16, 25, 1);
				margin-bottom: 32rpx;
				// 超出显示省略号
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}

			.rate {
				display: flex;
				align-items: center;
			}

			.rate,
			.time {
				font-size: 28rpx;
				font-weight: 400;
				color: rgba(103, 117, 133, 1);
				margin-bottom: 26rpx;
			}
		}

		.item-top-right {
			width: 150rpx;
			display: flex;
			flex-direction: column;
			justify-content: flex-end;
			align-items: flex-end;

			.salesman {
				width: 100%;
				// 超出隐藏
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				text-align: right;
			}
		}
	}

	.item-bottom {
		display: flex;
		justify-content: space-between;

		>view {
			display: flex;
			align-items: center;
			justify-content: space-between;

			>text {
				font-size: 28rpx;
				font-weight: 500;
				color: rgba(103, 117, 133, 1);
				margin-left: 8rpx;
			}
		}
	}
}
.searchContent {
	padding: 0 32rpx;
	/deep/.u-radio-group--row {
		display: flex;
    	flex-direction: row;
    	flex-wrap: wrap;
		> view {
			padding: 8rpx 0;
			margin-right: 60rpx;
		}
	}
}
.search-item-box {
    /deep/.u-form-item__body__right {
        border: 2rpx solid rgba(103, 117, 133, 0.4);
        padding: 16rpx 16rpx;
        border-radius: 8rpx;
    }
}
.checkbox-group-box {
	display: flex;
	flex-wrap: wrap;
	/deep/.uni-label-pointer {
		display: flex;
    	align-items: center;
		margin-right: 32rpx;
	}
}
/deep/.uni-label-pointer {
	display: flex;
	align-items: center;
}
.radio-group-box {
	display: flex;
	flex-wrap: wrap;
	/deep/.uni-label-pointer {
		display: flex;
    	align-items: center;
		margin-right: 32rpx;
		line-height: 28px;
	}
}
/deep/.uni-radio-input {
	width: 18px;
	height: 18px;

}
</style>